// pages/showCity/showCity.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: 'https://armeco.happydoit.com/upload', // 服务器图片路径
    upload: false, // 是否展示上传图片窗口
    successUpload: false, // 是否展示上传成功弹窗
    luckyDraw: false, // 是否展示抽奖弹窗
    noWinning: false, // 是否展示未中奖弹窗
    winnerTicket: false, // 是否展示抽中门票弹窗
    receiveBox: false, // 是否展示抽中礼盒弹窗
    receiveTicket: false, // 是否展示抽中门票弹窗
    winnerPrize: false, // 是否展示信息填写弹窗
    receiveCoupon: false, // 是否展示抽中优惠券弹窗
    tempFilePaths: [], // 上传的照片
    uploadImg: '', // 上传成功后返回的路径
    index: 1, // 当前转盘的位置
    isRun: false, // 是否已经点击抽奖按钮
    drawPrize: null, // 抽中的奖品
    showCityList: false, // 是否展示城市列表
    cityList: [], // 城市列表
    cityName: '', // 确认的城市名称
    cityId: -1, // 确认的城市id
    windowHeight: "1443rpx", // 默认背景图片高度
    userName: '', // 填写的用户名
    userPhone: '', // 填写的手机号
    userIdCard: '', // 填写的身份证号
    userAddress: '', // 填写的联系地址
    cityPrizeId: 0, // 城市奖品id
    reciptid: '', // 更改礼品的id
    id: '', // 查询收货信息的id
    chooseCityName: '',
    chooseCityId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    if (options.id) {
      that.setData({
        id: options.id
      })
    }
    that.setData({
      canFocus: app.globalData.canFocus
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (that.data.id != '') {
      wx.request({
        url: app.globalData.requestUrl + '/api/city/getCityReciptInfoById',
        data: {
          reciptid: that.data.id
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
          "Cookie": "JSESSIONID=" + app.globalData.jessionId
        },
        success: function (res) {
          if (res.data.code == 'success') {
            wx.hideLoading();
            if (res.data.data.citygiftid == 2) { // 礼盒
              that.setData({
                winnerPrize: true,
                userName: res.data.data.realname,
                userPhone: res.data.data.phone,
                userAddress: res.data.data.shipaddr,
                cityPrizeId: res.data.data.citygiftid
              })
            } else if (res.data.data.citygiftid == 1) { // 门票
              that.setData({
                winnerTicket: true,
                userName: res.data.data.realname,
                userPhone: res.data.data.phone,
                userIdCard: res.data.data.idcard,
                cityPrizeId: res.data.data.citygiftid
              })
            }
          } else {
            wx.hideLoading();
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              mask: true
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    return {
        title: '让邓伦来我的芯愿城市，就靠你的助力了！',
        path: '/pages/stage/showCity/showCity',
        imageUrl: that.data.imageUrl + '/cityimages/share-img.png'
      }
  },

  // 授权获取用户昵称
  bindGetUserInfo: function (e) {
    let that = this;
    if (e.detail.errMsg == 'getUserInfo:ok') {
      wx.request({
        url: app.globalData.requestUrl + '/api/recipeInfo',
        data: {
            nickname: e.detail.userInfo.nickName
        },
        method: "POST",
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "JSESSIONID=" + app.globalData.jessionId
        },
        complete: function () {
            that.showCityList();
        }
      })
    }
  },

  // 放大图片
  magnifyingThose: function (e) {
    let arr = [];
    arr.push(e.currentTarget.dataset.src);
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },

  // 显示上传图片窗口
  showUpload: function () {
    let that = this;
    that.showCityList();
  },

  // 关闭上传图片窗口
  closeHelp: function () {
    this.setData({
      upload: false,
      tempFilePaths: []
    })
  },

  // 展示城市列表
  showCityList: function () {
    let that = this;
    wx.showLoading({
        title: '加载中',
        mask: true,
    });
    wx.request({
        url: app.globalData.requestUrl + '/api/city/citylist',
        data: {},
        method: "POST",
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "JSESSIONID=" + app.globalData.jessionId
        },
        success: function (res) {
            if (res.data.code == 'success') {
                wx.hideLoading();
                that.setData({
                    cityList: res.data.data.citylist
                })
            } else {
                wx.hideLoading();
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    mask: true
                })
            }
        }
    })
    that.setData({
        showCityList: true
    })
  },

  // 选择城市
  selectCity: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    that.setData({
        chooseCityName: name,
        chooseCityId: id
    })
  },

  // 确认城市
  sureCity: function () {
    let that = this;
    let chooseCityName = that.data.chooseCityName;
    let chooseCityId = that.data.chooseCityId;
    if (chooseCityName === '' || chooseCityId === -1) {
        wx.showToast({
            title: '请选择城市~',
            icon: 'none',
            mask: true,
        });
        return;
    };
    that.setData({
        showCityList: false,
        cityName: chooseCityName,
        cityId: chooseCityId,
    });
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          tempFilePaths: tempFilePaths,
          upload: true
        })
      },
    })
  },

  // 点击确认上传
  sureUpload: function () {
    let that = this;
    if (!that.data.tempFilePaths || that.data.tempFilePaths.length == 0) {
      wx.showToast({
        title: '还没有上传照片',
        icon: 'none',
        mask: true
      })
      return;
    }
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.uploadFile({
      url: app.globalData.requestUrl + '/api/city/imageUp',
      filePath: that.data.tempFilePaths[0],
      name: 'upfile',
      header: {
        'Content-Type': 'multipart/form-data',
        'charset': 'UTF-8',
        "Cookie": "JSESSIONID=" + app.globalData.jessionId
      },
      success(res) {
        wx.hideLoading();
        console.log(JSON.parse(res.data))
        if (JSON.parse(res.data).code == 'success') {
          that.setData({
            tempFilePaths: [],
            upload: false,
            uploadImg: JSON.parse(res.data).data
          })
          that.saveImage();
        } else {
          wx.showToast({
            title: JSON.parse(res.data.msg),
            icon: 'none',
            mask: true
          })
        }
      }
    })
  },

  // 新增图片
  saveImage: function () {
    let that = this;
    wx.showLoading({
      title: '加载中',
      mask: true,
    });
    wx.request({
        url: app.globalData.requestUrl + '/api/city/saveCityEffect',
        data: {
          imgurl: that.data.uploadImg,
          cityid: that.data.cityId
        },
        method: "POST",
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "JSESSIONID=" + app.globalData.jessionId
        },
        success: function (res) {
            if (res.data.code == 'success') {
                wx.hideLoading();
                that.setData({
                  photoList: res.data.data,
                  successUpload: true,
                })
            } else {
                wx.hideLoading();
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    mask: true
                })
            }
        }
    })
  },

  // 前往城市点赞
  toLikeCity: function () {
    wx.navigateTo({
      url: '/pages/stage/likeCity/likeCity',
    });
  },

  // 关闭上传成功弹窗
  closeSuccess: function () {
    let that = this;
    that.setData({
      successUpload: false
    })
  },

  // 点击抽奖
  drawLucky: function () {
    let that = this;
    wx.request({
      url: app.globalData.requestUrl + '/api/city/cityDrawing',
      data: {},
      method: "POST",
      header: {
          "Content-Type": "application/x-www-form-urlencoded",
          "Cookie": "JSESSIONID=" + app.globalData.jessionId
      },
      success: function (res) {
          if (res.data.code == 'success') {
              wx.hideLoading();
              that.setData({
                cityPrizeId: res.data.data.citypresent.id,
                successUpload: false
              })
            if (res.data.data.citypresent.id == 1) {//中门票
                that.setData({
                  receiveTicket: true
                })
            } else if (res.data.data.citypresent.id == 2) { //中礼盒
                that.setData({
                  receiveBox: true
                })
              } else if (res.data.data.citypresent.id == 3) {// 中优惠券
                that.setData({
                  receiveCoupon: true
                })
              }
          } else {
              wx.hideLoading();
              wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  mask: true
              })
              that.setData({
                successUpload: false
              })
          }
      }
    })
  },

  // 关闭抽中门票弹窗
  closeTicket: function () {
    this.setData({
      receiveTicket: false
    })
  },

  // 关闭门票信息填写
  closeTicketPrize: function () {
    this.setData({
      winnerTicket: false
    })
  },

  // 关闭抽奖弹窗
  closeDraw: function () {
    this.setData({
      luckyDraw: false,
    })
  },

  // 关闭未中奖弹窗
  closeNoWinning: function () {
    this.setData({
      noWinning: false
    })
  },

  // 关闭抽中礼品盒弹窗
  closeBox: function () {
    this.setData({
      receiveBox: false
    })
  },

  // 点击领取礼盒
  receiveBox: function () {
    this.setData({
      receiveBox: false,
      winnerPrize: true
    })
  },

  // 点击领取门票
  receiveTicket: function () {
    this.setData({
      receiveTicket: false,
      winnerTicket: true
    })
  },

  // 关闭信息收集弹窗
  closePrize: function () {
    this.setData({
      winnerPrize: false
    })
  },

  // 关闭抽中优惠券弹窗
  closeCoupon: function () {
    this.setData({
      receiveCoupon: false
    })
  },

  // 点击领取优惠券
  receiveCoupon: function () {
    wx.navigateToMiniProgram({
      appId: 'wx32be38d26e316e2c',
      path: 'pages/custompage/custompage?pageItemUrl=newspage/77107d40-21c8-46a7-a194-be33641e68c9.html&workType=1&workCode=890000001521',
      extraData: {
        url: 'heloo'
      },
      envVersion: 'release',
    })
  },

  // 开始抽奖
  start: function () {
    let that = this;
    // 如果已经点击抽奖了
    if (that.data.isRun == true) {
      return
    } else {
      that.setData({
        isRun: true
      })
    }
    // 清空已获得的奖品
    that.setData({
      drawPrize: null
    })
    wx.request({
      url: app.globalData.requestUrl + '/api/drawing',
      data: {

      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": "JSESSIONID=" + app.globalData.jessionId
      },
      success: function (res) {
        if (res.data.status == 0) {
          that.setData({
            resultPrizeLevel: res.data.data.prizeLevel
          })
          // 重置起始位置
          that.setData({
            index: 1
          })
          // 声明一个空数组用来存放相同等级的奖品
          let arr = [];
          for (let i = 0; i < that.data.prize.prizeInfoVOList.length; i++) {
            if (that.data.prize.prizeInfoVOList[i].prizeLevel == res.data.data.prizeLevel) {
              arr.push(that.data.prize.prizeInfoVOList[i])
            }
          }
          // 随机获取其中的某个奖品
          let arr_index = Math.floor((Math.random() * arr.length));
          // 获取到随机奖品的索引值
          let id = that.data.prize.prizeInfoVOList.indexOf(arr[arr_index])
          that.setData({
            id: res.data.data.prizeLevel
          })
          // 生成一个转的圈数
          let turns = Math.round((Math.random() + 6));
          // 获取总步数(圈数加上奖品等级-1)
          let level_index = 0;
          if (res.data.data.prizeLevel == 1) {
            level_index = 1
          } else if (res.data.data.prizeLevel == 2) {
            level_index = 3
          } else if (res.data.data.prizeLevel == 3) {
            level_index = 5
          } else if (res.data.data.prizeLevel == 4) {
            level_index = 7
          } else if (res.data.data.prizeLevel == 5) {
            level_index = 8
          } else if (res.data.data.prizeLevel == 6) {
            level_index = 2
          } else if (res.data.data.prizeLevel == 7) {
            level_index = 4
          } else {
            level_index = 6
          }
          let count = turns * 8 + level_index - 1;
          // 初始化步数
          let num = 0;
          // 初始化速度
          let speed = 400;
          // 计时器开始抽奖
          let timer = setInterval(function () {
            num++;
            that.setData({
              index: ++that.data.index
            });
            if (that.data.index > 8) {
              that.setData({
                index: 1
              })
            }
            // 当步数与随机数相等就停止转盘
            if (num >= count - 6) {
              clearInterval(timer)
              let endTimer = setInterval(function(){
                num++;
                that.setData({
                  index: ++that.data.index
                });
                if (that.data.index > 8) {
                  that.setData({
                    index: 1
                  })
                }
                if (num >= count) {
                  clearInterval(endTimer)
                  setTimeout(function(){
                    that.setData({
                      isRun: false,
                      winning: true,
                      drawPrize: arr[arr_index]
                    })
                  },1000)
                }
              },500)
            }
          }, 100)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            mask: true
          })
        }
      }
    })
  },

  // 获取填写的姓名
  getName: function (e) {
    this.setData({
      userName: e.detail.value
    })
  },

  // 获取填写的手机号
  getPhone: function (e) {
    this.setData({
      userPhone: e.detail.value
    })
  },

  // 获取填写的身份证号
  getIdCard: function (e) {
    this.setData({
      userIdCard: e.detail.value
    })
  },

  // 获取填写的联系地址
  getAddress: function (e) {
    this.setData({
      userAddress: e.detail.value
    })
  },

  // 提交信息
  submitInfo: function () {
    let that = this;
    if (that.data.cityPrizeId == 2) {
      if (!that.data.userName || that.data.userName == '') {
        wx.showToast({
          title: '请输入姓名',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userPhone || that.data.userPhone == 0 || that.data.userPhone == '') {
        wx.showToast({
          title: '请输入手机号',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userAddress || that.data.userAddress == '') {
        wx.showToast({
          title: '请输入联系地址',
          mask: true,
          icon: 'none'
        })
        return;
      };
    };
    if ( that.data.cityPrizeId == 1) {
      if (!that.data.userName || that.data.userName == '') {
        wx.showToast({
          title: '请输入姓名',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userPhone || that.data.userPhone == 0 || that.data.userPhone == '') {
        wx.showToast({
          title: '请输入手机号',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userIdCard || that.data.userIdCard == '' ||  that.data.userIdCard == 0) {
        wx.showToast({
          title: '请输入身份证号',
          mask: true,
          icon: 'none'
        })
        return;
      };
    }
    wx.showLoading({
      title: '加载中',
      mask: true,
    });
    wx.request({
        url: app.globalData.requestUrl + '/api/city/cityRecipeInfo',
        data: {
          realname: that.data.userName,
          phone: that.data.userPhone,
          shipaddr: that.data.userAddress,
          idcard: that.data.userIdCard,
          citypresentid: that.data.cityPrizeId,
          reciptid: that.data.id
        },
        method: "POST",
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "JSESSIONID=" + app.globalData.jessionId
        },
        success: function (res) {
            if (res.data.code == 'success') {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  mask: true
              })
              that.setData({
                winnerTicket: false,
                winnerPrize: false,
                receiveCoupon: false
              })
            } else {
                wx.hideLoading();
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    mask: true
                })
            }
        }
    })
  },

  // 修改信息(待定)
  updateInfo: function () {
    let that = this;
    if (that.data.cityPrizeId == 2) {
      if (!that.data.userName || that.data.userName == '') {
        wx.showToast({
          title: '请输入姓名',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userPhone || that.data.userPhone == 0 || that.data.userPhone == '') {
        wx.showToast({
          title: '请输入手机号',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userAddress || that.data.userAddress == '') {
        wx.showToast({
          title: '请输入联系地址',
          mask: true,
          icon: 'none'
        })
        return;
      };
    };
    if ( that.data.cityPrizeId == 1) {
      if (!that.data.userName || that.data.userName == '') {
        wx.showToast({
          title: '请输入姓名',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userPhone || that.data.userPhone == 0 || that.data.userPhone == '') {
        wx.showToast({
          title: '请输入手机号',
          mask: true,
          icon: 'none'
        })
        return;
      };
      if (!that.data.userIdCard || that.data.userIdCard == '' ||  that.data.userIdCard == 0) {
        wx.showToast({
          title: '请输入身份证号',
          mask: true,
          icon: 'none'
        })
        return;
      };
    }
    wx.showLoading({
      title: '加载中',
      mask: true,
    });
    wx.request({
        url: app.globalData.requestUrl + '/api/city/cityRecipeInfo',
        data: {
          realname: that.data.userName,
          phone: that.data.userPhone,
          shipaddr: that.data.userAddress,
          idcard: that.data.userIdCard,
          citypresentid: that.data.cityPrizeId,
          reciptid: that.data.reciptid
        },
        method: "POST",
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "JSESSIONID=" + app.globalData.jessionId
        },
        success: function (res) {
            if (res.data.code == 'success') {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  mask: true
              })
              that.setData({
                winnerTicket: false,
                winnerPrize: false,
                receiveCoupon: false
              })
            } else {
                wx.hideLoading();
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    mask: true
                })
            }
        }
    })
  },

  showFocus() {
    this.setData({
      isFocus: true
    })
  },

  hideFocus() {
    this.setData({
      isFocus: false
    })
  },

  openRule() {
    this.setData({
      showRule: true
    })
  },

  onGetCode: function (e) {
    this.setData({
      showRule: e.detail.val
    })
  }
})